package models

import (
	orm "go-admin/common/global"
	"gorm.io/gorm"
	"time"
)

/**
* @Description:
* @Author: yuweizhu
* @Date: 2020/11/22 8:47 下午
**/
type TAccount struct {
	ID        int64 `json:"id"`
	UserId    int64 `json:"userId"`
	Amount    int `json:"amount"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	SumAmount int `json:"sumAmount"`
	RemainRights int `json:"remainRights" gorm:"-"`
}

func (TAccount) TableName() string {
	return "t_account"
}

// 获取用户数据
func (e *TAccount) Get() (account TAccount, err error) {

	table := orm.GetDb().Table(e.TableName()).Select([]string{"t_account.*"})
	if e.UserId != 0 {
		table = table.Where("user_id = ?", e.UserId)
	}

	if err = table.First(&account).Error; err != nil {
		return
	}

	var amount int
	err = orm.GetDb().Table(TRights{}.TableName()).Select("COALESCE(sum(remain_value), 0)").Where(
		"user_id = ? AND end_time > NOW() AND remain_value >= 0", e.UserId).Row().Scan(&amount)
	account.RemainRights = amount
	return
}

//添加
func (e *TAccount) Insert() (err error) {
	if err = orm.GetDb().Table(e.TableName()).Create(&e).Error; err != nil {
		return
	}
	return
}

func (e *TAccount) IncreaseAmount(tx *gorm.DB) error {
	sql := "UPDATE t_account set amount = amount + ?, sum_amount = sum_amount + ?, " +
		"updated_at = NOW() where user_id = ? and amount >=0"
	return tx.Exec(sql, e.Amount, e.Amount, e.UserId).Error
}

func (e *TAccount) ValidateAmount() int64 {
	var count int64
	orm.GetDb().Table(e.TableName()).Where("user_id = ? AND amount >= ?", e.UserId, e.Amount).Count(&count)
	return count
}

func (e *TAccount) DecreaseAmount(tx *gorm.DB) error {
	sql := "UPDATE t_account set amount = amount - ?, " +
		"updated_at = NOW() where user_id = ? and amount >=0"
	return tx.Exec(sql, e.Amount, e.UserId).Error
}
